package com.bms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.bms.domain.Comment;
import com.bms.domain.Event;
import com.bms.domain.User;

public class CommentDao {
	
	private JdbcTemplate jdbcTemplate;
	private UserDao userDao;
	private EventDao eventDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setEventDao(EventDao eventDao) {
		this.eventDao = eventDao;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	@SuppressWarnings("unchecked")
	public List<Comment> getCommentList(String eventId, String userId) {
		String sql = "select * from bms_comment where eventid=? and userid=? order by id desc";
		List<Comment> list = this.jdbcTemplate.query(sql,new Object[]{eventId,userId},new rowMapper());
		return list;
	}
	
	
	public int addComment(Comment comment){
		String sql = "insert into bms_comment values(default,?,?,?,?,?)";
		Object[] args = new Object[]{comment.getEvent().getId(),
								     comment.getUser().getId(),
						     		 comment.getCreatetime(),
						     		 comment.getContent(),
						     		 comment.getRepeat()
		};
		return this.jdbcTemplate.update(sql, args);
	}
	
	
	
	public class rowMapper implements RowMapper {

		@Override
		public Object mapRow(ResultSet rs, int arg1) throws SQLException {
			Comment c = new Comment();
			c.setId(rs.getString("id"));
			Event event = eventDao.getEvent(rs.getString("eventid"));
			c.setEvent(event);
			User user = userDao.getUserFromId(rs.getString("userid"));
			c.setUser(user);
			c.setCreatetime(rs.getString("createtime"));
			c.setContent(rs.getString("content"));
			c.setRepeat(rs.getString("repeat"));
			return c;
		}
		
	}
}
